import 'package:flutter/material.dart';
import 'package:flutterarticle/bean/article_bean.dart';
import 'package:flutterarticle/db/database.dart';
import 'package:flutterarticle/generated/i18n.dart';
import 'package:flutterarticle/network/api.dart';
import 'package:flutterarticle/pages/starred_list/starred_list_page.dart';
import 'package:flutterarticle/utils/constant.dart';
import 'package:flutterarticle/utils/date_util.dart';
import 'package:flutterarticle/utils/sp_store_util.dart';
import 'package:share/share.dart';

class HomePage extends StatefulWidget {
  final ArticleBean article; //文章内容  日期作者 等

  HomePage(this.article);

  @override
  State<StatefulWidget> createState() => _HomePageState(article);
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  ArticleBean article;
  String date = formatDate(DateTime.now());

  _HomePageState(this.article);

  double _fontSize = 18;//字体
  TabController _tabController;
  int _themeColorIndex = 0;//主题
  ArticleProvider provider;

  double horDistance = 0.0; //判断滑动方向

  @override
  void initState() {
    super.initState();

    _tabController = TabController(length: 5, vsync: this);
    provider = ArticleProvider(); //数据操作
    getFontSize()
        .then((value) {
          if (value != _fontSize) {
            _fontSize = value;
          }
        })
        .then((value) => getThemeColor())
        .then((value) {
          if (value != _themeColorIndex) {
            setState(() {
              _themeColorIndex = value;
              _tabController.index = value;
            });
          }
        });
  }

  @override
  void didChangeDependencies() {
    // S.of(context) must call after _HomePageState.initState() completed.
    print('disChanged....'+article.toString());
    if (article == null) { //有收藏列表 pop过来的数据
      loadData(date);
    }
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _tabController.dispose();
    provider.getDB().then((db) => db.close());//关闭数据库
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(article.data.title),
        centerTitle: true,
        leading: IconButton(icon: Icon(Icons.menu), onPressed: _bottomMenu),
        actions: <Widget>[
          IconButton( //分享按钮
            icon:Icon(Icons.share,color: Colors.white,),
            onPressed: onShare,
          ),
          IconButton(//收藏按钮
            icon: Icon(article.starred ? Icons.star : Icons.star_border),
            onPressed: onStarPressed,
          ),
        ],
        backgroundColor: themeColors[_themeColorIndex],
      ),
      body: ListView(
        children: [
          Text.rich(
            TextSpan(//文章介绍 作者 字数 时间等
                text: article?.data?.date == null
                    ? ""
                    : "(${getRelatedTime(context, str2Date(article.data.date.curr))}，${S.of(context).author}：${article.data.author}，${S.of(context).word_count}：${article.data.wc})",
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: _fontSize - 3,
                  height: 1.4,
                )),
            textAlign: TextAlign.end,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          InkWell(
            onTap: () {
              if (article?.data?.date == null) {
                loadData(date);
              } else {
                return true;
              }
            },
            child: Container(
              child:GestureDetector(
                child:  Text(
                  article?.data?.content,
                  style: TextStyle(fontSize: _fontSize),
                  textAlign: TextAlign.start,
                ),
                onHorizontalDragStart: (DragStartDetails e) {
                  print("用户手指按下：${e.globalPosition}");
                  horDistance=0;
                },
                onHorizontalDragUpdate:(DragUpdateDetails e) {
                  setState(() {
                    horDistance += e.delta.dx;
                    print('手指滑动'+horDistance.toString());
                  });
                },
                onHorizontalDragEnd: (DragEndDetails e){
                  if(horDistance>0)
                    print('左滑 结束'+horDistance.toString());
                  else {
                    print('右滑 结束' + horDistance.toString());
                    loadData('random');
                  }
                },
              ),


              color: article.data.date == null
                  ? Colors.transparent
                  : Theme.of(context).canvasColor,
            ),
          )
        ],
        padding: const EdgeInsets.all(10),
      ),
    );
  }

  //收藏
  void onStarPressed() {
    setState(() {
      article.starred = !article.starred;
    });
    provider.insertOrReplaceToDB(article); //文章存入数据库
  }

  void onShare(){
    print("分享url");
    Share.share('《${article.data.title}》'+'\n${article.data.content}');
  }

  void _bottomMenu() {

    Navigator.push(
        context,
        MaterialPageRoute( //路由到收藏列表
            builder: (context) => StarredListPage(
                themeColors[_themeColorIndex])))
        .then((result) {
      if (result is ArticleBean) { //返回的结果是 文章类型
        // Clicked a starred article and back
        //点击 收藏列表文章
        setState(() {
          article = result;
          date = article.date;
        });
      } else {
        // Normally back, check current article's starred state
        provider
            .getFromDB(article.date)
            .then((articleBean) {
          if (articleBean != null &&
              articleBean.starred != article.starred) {
            setState(() =>
            article.starred = articleBean.starred);
          }
        });
      }
    });
  }

  void loadData(String date) {
    article = ArticleBean();
    article.data = DataBean();
    if (date != "random") {
      this.date = date;
    }
    article.data.title = S.of(context).action_loading; //标题变为 正在加载
    article.data.content = S.of(context).action_loading; //内容变为 正在加载
    article.starred = false;
    setState(() {});
    Article.getArticle(date: date).then((article) {
      setState(() {
        this.date = article.date;
        this.article = article;
      });
    }).catchError((e) {
      print(e);
      setState(() {
        article.data.title = S.of(context).action_load_error;
        article.data.content = S.of(context).content_load_error;
        this.article = article;
      });
    });
  }
}
